import Layout from "@/layouts/index.vue"
import ParentView from "@/components/ParentView/index.vue"
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('@/views/**/*.vue')

export const buildRouters = (menus: any) => {
  let returnRouters: any = [];

  if (!menus || !Array.isArray(menus) || menus.length == 0) {
    return returnRouters;
  }
  // for循环遍历
  for (let i = 0;i < menus.length;i++) {
    returnRouters.push(buildMenu(menus[i], ""));
  }
  return returnRouters;
}

const buildChildren = (menus: any) => {
  let returnRouters: any = [];
  // for循环遍历
  for (let i = 0;i < menus.length;i++) {
    let menu = menus[i];
    let menuPath = menu.path;
    returnRouters.push(buildMenu(menu, menuPath));
  }
  return returnRouters;
}

const buildMenu = (menu: any, parentPath: string) => {
  if (!menu || Object.keys(menu).length == 0) {
    return null;
  }
  let { path, menuCmptWeb, menuRouteName, children } = menu;
  let component = menuCmptWeb == "Layout" ? Layout : menuCmptWeb == 'ParentView' ? ParentView : loadCmpt(menuCmptWeb);
  path = (parentPath ? parentPath + path : path);
  return {
    path,
    name: menuRouteName,
    component,
    children: (!children || !Array.isArray(children) && children.length == 0 ? null : buildChildren(children))
  }
}

const loadCmpt = (menuCmptWeb: string) => {
  let cmptPath = `/src/views/menus${menuCmptWeb}.vue`;
  for (const path in modules) {
    if (path.toLowerCase() == cmptPath.toLowerCase()) {
      return modules[path];
    }
  }
}